﻿
using BoilenEditor.Primitives;
using BoilenEditor.Primitives.Snippets;
using BoilenEditor.Properties;
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace BoilenEditor {

    public partial class SnippetWindow : Window {

        private static readonly ImplementerData SnippetData = new ImplementerData( );

        private readonly bool showDescription_;


        public SnippetWindow( Window owner, bool showDescription ) {
            InitializeComponent( );

            this.Owner = owner;
            this.DataContext = SnippetData;
            this.showDescription_ = showDescription;

            this.DeclarationItems.SortDescriptions.Add( new SortDescription( "Category", ListSortDirection.Ascending ) );
            this.DeclarationItems.SortDescriptions.Add( new SortDescription( "DisplayName", ListSortDirection.Ascending ) );
            if( !showDescription )
                this.argumentsList_.Items.Filter = obj => !((ArgumentData)obj).IsDescription;
        }


        public DeclarationData Declaration {
            get { return (DeclarationData)this.declarationsSelector_.SelectedItem; }
        }

        private ItemCollection DeclarationItems {
            get { return this.declarationsSelector_.Items; }
        }


        private void SelectCanExecute( object sender, CanExecuteRoutedEventArgs e ) {
            var declaration = (DeclarationData)this.declarationsSelector_.GetValueOrDefault( cb => cb.SelectedItem, null );
            if( declaration.HasValue( ) && declaration.Arguments.All( a => (!this.showDescription_ && a.IsDescription) || !string.IsNullOrEmpty( a.Value ) ) )
                e.CanExecute = true;
        }

        private void SelectExecuted( object sender, ExecutedRoutedEventArgs e ) {
            Settings.Default.Save( );

            this.DialogResult = true;
        }

        private void CancelExecuted( object sender, ExecutedRoutedEventArgs e ) {
            this.Close( );
        }

        protected override void OnClosed( EventArgs e ) {
            base.OnClosed( e );

            Settings.Default.Reload( );
        }

    }

}
